package com.yt.website.action;

import com.yt.core.MsgBean;
import com.yt.util.RandomUtil;
import com.yt.website.action.base.BaseAction;
import com.yt.website.exception.DataException;
import com.yt.website.util.SmsUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/")
public class MobileCodeAction extends BaseAction {
    private static Log logger = LogFactory.getLog(MobileCodeAction.class);
    private static String TIME_KEY = "LastSendMobileCodeTime";
    private static String CODE_KEY = "MobileCode";

    @RequestMapping("/sendMobileCode")
    public
    @ResponseBody
    Object sendMobileCode(@RequestParam(value = "mobile", required = true) String mobile,
                HttpServletRequest request) throws Exception {
        MsgBean msg = new MsgBean();

        long lastSentTime = 0l;
        Object obj = request.getSession().getAttribute(TIME_KEY);
        if (obj != null) {
            lastSentTime = Long.parseLong(obj.toString());
        }

        long currTime = System.currentTimeMillis() / 1000;
        if (currTime >= lastSentTime + 60) {
            long random = RandomUtil.getRandom(6);
            request.getSession().setAttribute(CODE_KEY, random);
            request.getSession().setAttribute(TIME_KEY, currTime);
            logger.info(mobile + "的验证码是：" + random);
            String sms = "感谢您注册怡天网会员，您的验证码是" + random + "，如非本人操作请忽略。";
            boolean result = SmsUtil.send(sms, mobile);
            if(!result){
                throw new DataException("验证码发送失败， 请重试！");
            }
        } else {
            throw new DataException("60秒内只能发送一次手机验证码，请稍等!");
        }
        return msg.returnMsg();
    }

    /**
     * 验证验证码是否正确
     *
     * @param code
     * @param request
     * @return
     */
    public static boolean checkCode(String code, HttpServletRequest request) {
        Object obj = request.getSession().getAttribute(CODE_KEY);
        if (obj != null) {
            String realCode = obj.toString();
            if (realCode.toLowerCase().equals(code.toLowerCase())) {
                return true;
            }
        }
        return false;
    }

}
